<?php


namespace app\admin\controller;


use app\admin\services\hwObs\Obs;
use app\admin\services\hwObs\ObsServices;
use think\admin\Controller;
use think\admin\extend\DataExtend;
use think\App;

/**
 * 店员管理
 * Class ShopClerk
 * @package app\admin\controller
 */
class ShopClerk extends Controller
{
    /**
     * 绑定数据表
     * @var string
     */
    private $table = 'lgShopClerks';

    private $sex = [
        0 => '未知',
        1 => '男',
        2 => '女',
    ];

    private $status = [
        1 => '正常',
        2 => '冻结',
        3 => '离职',
    ];

    /**
     * 店铺id
     * @var mixed|string
     */
    protected $shop_id = '';

    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->shop_id = !empty(session('shop_info.shop_id')) ? session('shop_info.shop_id') : '';
    }

    /**
     * 店员列表
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @auth true
     * @login true
     */
    public function index()
    {
        //标题
        $this->title = '店员管理';
        $where = $map = [];
        //数据权限
        if (!empty($this->shop_id)) {
            $map[] = ['id', 'IN', $this->shop_id];
        }
        //门店
        $distributor = $this->app->db->table('lg_distributor')->where($map)->order('id asc')->column('name', 'id');
        $this->assign('distributor', $distributor);
        //搜索
        $name = input('name');
        $create_at = input('create_at');
        $shop_id = input('shop_id');
        if ($name) {
            $where[] = ['c.name', 'like', '%' . $name . '%'];
        }
        if ($create_at) {
            $create_at = explode(' - ', $create_at);
            $where[] = ['c.create_time', 'between time', $create_at];
        }
        $query = $this->_query($this->table);
        $query->alias('c');
        $query->where($where);
        if ($shop_id) {
            $query->where('FIND_IN_SET(:shop_id,`shop_id`)', ['shop_id' => $shop_id]);
        }
        //数据权限
        if (!empty($this->shop_id)) {
            $query->whereIn('shop_id', $this->shop_id);
        }
        $query->order('c.id desc')->page();
    }

    /**
     * 列表数据处理
     * @param $data
     */
    protected function _index_page_filter(&$data)
    {
        $distributor_list = $query = $this->app->db->name('lgDistributor')->column('name', 'id');
        foreach ($data as $key => $value) {
            $value['sex_title'] = $this->sex[$value['sex']] ?? '-';
            $value['status_title'] = $this->status[$value['status']] ?? '-';
            if ($value['shop_id']) {
                $id_list = explode(',', $value['shop_id']);
                $item = [];
                if (is_array($id_list) && count($id_list) > 0) {
                    foreach ($id_list as $k => $vo) {
                        if (isset($distributor_list[$vo]) && $distributor_list[$vo]) {
                            $item[] = $distributor_list[$vo];
                        }
                    }
                }
                if ($item) {
                    $value['shop_names'] = implode(',', $item);
                } else {
                    $value['shop_names'] = '';
                }
            }
            $data[$key] = $value;
        }
    }

    /**
     * 添加店员
     * @auth true
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @auth true
     * @login true
     */
    public function add()
    {
        $this->_applyFormToken();
        //数据权限
        $map = [];
        if (!empty($this->shop_id)) {
            $map[] = ['id', 'IN', $this->shop_id];
        }
        //门店
        $distributor = $this->app->db->table('lg_distributor')->where($map)->order('id asc')->field('name,id')->select();
        $this->assign('distributor', json_encode($distributor, JSON_UNESCAPED_UNICODE));
        if ($this->request->isPost()) {
            $data = $this->request->param();
            $vailResult = $this->app->validate->check($data, [
                'phone|号码' => 'require|mobile',
                'portrait|头像' => 'require'
            ]);
            if ($vailResult !== true) {
                $this->error($this->app->validate->getError());
            }
            $img = $data['portrait'];
            $faceId = $this->getFaceId($img);
            if ($faceId == false) {
                $this->error('添加faceid失败');
            }
            $saveData = [
                'number' => $data['number'],
                'shop_id' => $data['shop_id'],
                'name' => $data['name'],
                'sex' => $data['sex'],
                'portrait' => $img,
                'phone' => $data['phone'],
                'id_card' => $data['id_card'] ?? '',
                'position' => $data['position'],
                'work_detail' => $data['work_detail'],
                'status' => $data['status'],
                'department_id' => $data['department_id']
            ];
            $saveData['face_id'] = $faceId;
            $saveData['create_time'] = time();
            $result = $this->app->db->name($this->table)->insert($saveData);
            if ($result) {
                sysoplog('店员管理', '添加店员成功');
                $this->success('添加成功');
            }
            $this->error('添加失败');
        }
        $this->_form($this->table, 'form');
    }

    /**
     * 编辑店员
     * @auth true
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @auth true
     * @login true
     */
    public function edit()
    {
        $this->_applyFormToken();
        //数据权限
        $map = [];
        if (!empty($this->shop_id)) {
            $map[] = ['id', 'IN', $this->shop_id];
        }
        //门店
        $distributor = $this->app->db->table('lg_distributor')->where($map)->order('id asc')->field('name,id')->select();
        $this->assign('distributor', json_encode($distributor, JSON_UNESCAPED_UNICODE));
        sysoplog('店员管理', '修改店员信息成功');
        $this->_form($this->table, 'form');
    }

    /**
     * 处理表单数据
     * @param $data
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    protected function _form_filter(&$data)
    {
        //部门列表
        $departmentName = $this->app->db->name('lg_department')->select()->toArray();
        $departmentList = DataExtend::arr2table($departmentName);
        $this->assign(['departmentName' => $departmentList]);
        if ($this->request->isPost()) {
            $params = $this->request->param();
            if (isset($params['id'])) {
                $data['update_time'] = time();
            } else {
                $data['create_time'] = time();
                $data['update_time'] = time();
            }
        }
    }

    /**
     * 删除店员
     * @auth true
     * @throws \think\db\exception\DbException
     * @auth true
     * @login true
     */
    public function remove()
    {
        $this->_applyFormToken();
        sysoplog('店员管理', '删除数据成功');
        $this->_delete($this->table);
    }

    /**
     * 删除回调
     * @param $result
     */
    protected function _remove_delete_result($result)
    {
        if ($result) {
            $id = input('id', 0);
            $info = $this->app->db->table('lg_shop_clerks')->where('id', $id)->field('face_id,portrait')->find();
            $this->delFaceId($info['face_id']);
            $this->delObsImg($info['portrait']);
            sysoplog('店员管理', '删除id为' . $id . '的店员成功');
        } else {
            $this->error("删除失败");
        }
    }

    public function delObsImg($portrait)
    {
        $url = parse_url($portrait);
        $path = $url['path'] ?? '';
        $path = substr($path, strripos($path, "_") + 1);
        if ($path) {
            $obs = new ObsServices();
            $result = $obs->delete_obs_file($path);
            sysoplog('店员管理', $result);
        }
    }


    /**
     * 删除faceId
     * @param $faceId
     * @return bool
     */
    protected function delFaceId($faceId)
    {
        $url = "http://124.71.36.111:8095/monitor/frs/face?faceId={$faceId}";
        $result = send_request($url, 'DELETE');
        if (isset($result['httpCode']) && $result['httpCode'] == 200) {
            $resArr = json_decode($result['data'], true);
            p($resArr);//调试
            if ($resArr['success']) {
                return true;
            } else {
                return false;
            }
        }
        return false;
    }


    /**
     * 获取faceid
     * @param $img
     * @return bool|string
     */
    protected function getFaceId($img)
    {
        $url = 'http://124.71.36.111:8095/monitor/frs/face/uploadByUrl';
        $data = json_encode(['imageUrl' => $img]);
        $headerArray = array("Content-type:application/json;charset='utf-8'", "Accept:application/json");
        $result = curl_post_request($url, $data, $headerArray);
        if (isset($result['success']) && $result['success'] == true) {
            $faceId = $result['data']['faces'][0]['face_id'] ?? '';
            if (empty($faceId)) {
                return false;
            }
            return $faceId;
        }
        return false;
    }

    public function uploadImg()
    {
        $file = request()->file('file');
        $filename = $_FILES['file']['name'];
        $suffix = substr(strrchr($filename, '.'), 1);
        $obs = new ObsServices();
        $path = $obs->upload_obs_file($file, 0, $suffix);
        return json(['code' => 200, 'msg' => '上传成功', 'data' => $path]);
    }
}